﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Dungeon_Dive
{
    public class FPSCounter : DrawableGameComponent
    {
        private Game parentGame;
        private int frames;
        private TimeSpan elapsedTime;
        private SpriteBatch spriteBatch;
        public int FPS { get; set; }
        public SpriteFont Font { get; set; }
        private Log log;

        public FPSCounter(Game game)
            : base(game)
        {
            parentGame = game;
            Font = null;
            FPS = -1;
            elapsedTime = TimeSpan.Zero;
        }

        public override void Update(GameTime gameTime)
        {
            elapsedTime += gameTime.ElapsedGameTime;
            if (elapsedTime > TimeSpan.FromSeconds(1)) //One second has elapsed, our fps is how many frames were drawn
            {
                FPS = frames;
                frames = 0;
                elapsedTime -= TimeSpan.FromSeconds(1);
            }
            base.Update(gameTime);
        }

        public override void Initialize()
        {
            log = (Log)parentGame.Services.GetService(typeof(Log));
            log.Write("FPSCounter.Initialize()");
            
            base.Initialize();
        }

        protected override void LoadContent()
        {
            log.Write("FPSCounter.LoadContent()");
            ContentManager contentManager = (ContentManager)parentGame.Services.GetService(typeof(ContentManager));
            spriteBatch = contentManager.SpriteBatch;

            base.LoadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            ++frames;
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);
            spriteBatch.DrawString(Font, "FPS:" + FPS.ToString(), new Vector2(2, 2), Color.White);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
